document.addEventListener('DOMContentLoaded', function() {
    // 获取用户ID从URL
    const userId = window.location.pathname.split('/').pop();
    
    // 加载图表数据
    loadConsumptionTrend(userId);
    loadShoppingPreference(userId);
    
    // 设置事件监听器
    setupEventListeners(userId);
});

function loadConsumptionTrend(userId) {
    fetch(`/api/users/${userId}/consumption-trend`)
        .then(response => response.json())
        .then(data => {
            const trace = {
                x: data.dates,
                y: data.amounts,
                type: 'scatter',
                mode: 'lines+markers',
                line: {
                    color: '#007bff',
                    width: 2
                },
                marker: {
                    color: '#007bff',
                    size: 6
                }
            };

            const layout = {
                margin: { t: 20, r: 20, l: 50, b: 40 },
                xaxis: {
                    title: '日期',
                    showgrid: false
                },
                yaxis: {
                    title: '消费金额 (¥)',
                    showgrid: true,
                    gridcolor: '#f0f0f0'
                },
                paper_bgcolor: 'rgba(0,0,0,0)',
                plot_bgcolor: 'rgba(0,0,0,0)'
            };

            Plotly.newPlot('consumptionTrendChart', [trace], layout);
        });
}

function loadShoppingPreference(userId) {
    fetch(`/api/users/${userId}/shopping-preference`)
        .then(response => response.json())
        .then(data => {
            const trace = {
                labels: data.categories,
                values: data.amounts,
                type: 'pie',
                hole: 0.4,
                marker: {
                    colors: [
                        '#007bff',
                        '#28a745',
                        '#ffc107',
                        '#dc3545',
                        '#6c757d',
                        '#17a2b8'
                    ]
                }
            };

            const layout = {
                margin: { t: 20, r: 20, l: 20, b: 20 },
                showlegend: true,
                legend: {
                    orientation: 'h',
                    y: -0.1
                },
                paper_bgcolor: 'rgba(0,0,0,0)',
                plot_bgcolor: 'rgba(0,0,0,0)'
            };

            Plotly.newPlot('shoppingPreferenceChart', [trace], layout);
        });
}

function setupEventListeners(userId) {
    // 订单分页事件
    document.getElementById('orderPagination').addEventListener('click', (e) => {
        e.preventDefault();
        const pageLink = e.target.closest('.page-link');
        if (pageLink) {
            const page = pageLink.dataset.page;
            loadOrderHistory(userId, page);
        }
    });

    // 标签编辑
    const saveTagsBtn = document.getElementById('saveTagsBtn');
    if (saveTagsBtn) {
        saveTagsBtn.addEventListener('click', () => {
            const selectedTags = Array.from(document.querySelectorAll('#availableTags .tag-item.selected'))
                .map(tag => tag.dataset.id);

            fetch(`/api/users/${userId}/tags`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    tag_ids: selectedTags
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                }
            });
        });
    }

    // 标签搜索
    const tagSearch = document.getElementById('tagSearch');
    if (tagSearch) {
        let searchTimeout;
        tagSearch.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                const searchTerm = e.target.value;
                filterTags(searchTerm);
            }, 300);
        });
    }
}

function loadOrderHistory(userId, page = 1) {
    fetch(`/api/users/${userId}/orders?page=${page}`)
        .then(response => response.json())
        .then(data => {
            renderOrderHistory(data.orders);
            renderOrderPagination(data.total_pages, data.current_page);
        });
}

function renderOrderHistory(orders) {
    const tbody = document.getElementById('orderHistory');
    tbody.innerHTML = orders.map(order => `
        <tr>
            <td>${order.order_number}</td>
            <td>${order.order_date}</td>
            <td>¥${order.total_amount}</td>
            <td>
                <span class="badge bg-${order.status_color}">${order.status}</span>
            </td>
            <td>
                <button class="btn btn-sm btn-info" onclick="viewOrderDetails('${order.id}')">
                    查看详情
                </button>
            </td>
        </tr>
    `).join('');
}

function renderOrderPagination(totalPages, currentPage) {
    const pagination = document.getElementById('orderPagination');
    pagination.innerHTML = '';

    // Previous button
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" data-page="${currentPage - 1}">
            <i class="mdi mdi-chevron-left"></i>
        </a>
    `;
    pagination.appendChild(prevLi);

    // Page numbers
    for (let i = 1; i <= totalPages; i++) {
        const li = document.createElement('li');
        li.className = `page-item ${i === currentPage ? 'active' : ''}`;
        li.innerHTML = `
            <a class="page-link" href="#" data-page="${i}">${i}</a>
        `;
        pagination.appendChild(li);
    }

    // Next button
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" data-page="${currentPage + 1}">
            <i class="mdi mdi-chevron-right"></i>
        </a>
    `;
    pagination.appendChild(nextLi);
}

function filterTags(searchTerm) {
    const tags = document.querySelectorAll('#availableTags .tag-item');
    tags.forEach(tag => {
        const tagName = tag.textContent.toLowerCase();
        if (tagName.includes(searchTerm.toLowerCase())) {
            tag.style.display = '';
        } else {
            tag.style.display = 'none';
        }
    });
}

function viewOrderDetails(orderId) {
    fetch(`/api/orders/${orderId}`)
        .then(response => response.json())
        .then(data => {
            const modal = document.getElementById('orderDetailsContent');
            modal.innerHTML = `
                <div class="order-details">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <p><strong>订单号：</strong>${data.order_number}</p>
                            <p><strong>下单时间：</strong>${data.order_date}</p>
                            <p><strong>订单状态：</strong>
                                <span class="badge bg-${data.status_color}">${data.status}</span>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>支付方式：</strong>${data.payment_method}</p>
                            <p><strong>支付时间：</strong>${data.payment_time}</p>
                            <p><strong>订单金额：</strong>¥${data.total_amount}</p>
                        </div>
                    </div>
                    <h6>订单商品</h6>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>商品名称</th>
                                    <th>数量</th>
                                    <th>单价</th>
                                    <th>小计</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.items.map(item => `
                                    <tr>
                                        <td>${item.name}</td>
                                        <td>${item.quantity}</td>
                                        <td>¥${item.price}</td>
                                        <td>¥${item.subtotal}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
            $('#orderDetailsModal').modal('show');
        });
}
